<template class="qwe">
  <div class="qwe">
    <div class="container">
      <div class="announce-box" v-for="(item, index) in annoList">
        <!-- 文本内容 -->
        <div v-html="item.context" class="comment">
        </div>
        <!-- 最后编辑时间 -->
        <div class="last-time">
          <el-button type="warning" link @click="editAnnounce(item)" v-if="role=='teacher'"
            >修改公告</el-button
          >
          <el-popconfirm
            confirm-button-text="Yes"
            cancel-button-text="No"
            icon-color="#626AEF"
            title="Are you sure to delete this?"
            @confirm="deleteAnnounce(item)"
            @cancel="cancelEvent"
          >
            <template #reference>
              <el-button type="danger" v-if="role=='teacher'" link>删除公告</el-button>
            </template>
          </el-popconfirm>
          <span
            style="
              color: rgb(177, 170, 188);
              font-size: 13px;
              padding-right: 20px;
              margin-left: 20px;
            "
            >{{ item.createTime }}</span
          >
        </div>
        <el-divider style="margin: 0px" />
      </div>
      <!-- 点击加载更多 -->
      <div class="more" v-if="isMore">
        <el-button type="primary" link @click="getMore()">加载更多</el-button>
      </div>
      <div v-if="!isMore">
        <el-divider content-position="center">我也是有底线的！</el-divider>
      </div>
    </div>
    <div class="right-box" v-if="role=='teacher'">
      <el-button type="primary" round @click="creatAnnounce()"
        >发布公告</el-button
      >
    </div>
  </div>
  <!-- 新增 -->
  <el-dialog
    v-model="dialogVisible"
    title="发布公告"
    width="60%"
    destroy-on-close
    center
  >
    <div style="border: 1px solid #ccc">
      <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        :mode="mode"
      />
      <Editor
        style="height: 500px; overflow-y: hidden"
        v-model="valueHtml"
        :defaultConfig="editorConfig"
        :mode="mode"
        @onCreated="handleCreated"
      />
    </div>
        <div style="margin-top: 10px">
      <div style="padding-left: 90%">
        <el-button @click="deliverAnno()" type="primary">完成</el-button>
      </div>
    </div>
  </el-dialog>
  <!-- 修改 -->
  <el-dialog
    v-model="changeDialogVisible"
    title="修改公告"
    width="60%"
    destroy-on-close
    center
  >
    <div style="border: 1px solid #ccc">
      <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        :mode="mode"
      />
      <Editor
        style="height: 500px; overflow-y: hidden"
        v-model="valueHtml"
        :defaultConfig="editorConfig"
        :mode="mode"
        @onCreated="handleCreated"
      />
    </div>
    <div style="margin-top: 10px">
      <div style="padding-left: 90%">
        <el-button @click="deliverChangedAnno()" type="primary">完成</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { onBeforeUnmount, ref, shallowRef } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { useRoute } from "vue-router";
import { mapGetters } from "vuex";
import {
  queryByPage,
  addAnno,
  deleteAnnoByID,
  editAnno,
  countAnno,
} from "../../api/course.js";
import { ElMessage } from "element-plus";
export default {
  components: { Editor, Toolbar },
  setup() {
    // 适用于富文本的图片上传服务 file图片的上传参数  第二个就是返回后数据插入到富文本编辑器的内容
    const update = (file, insertFn) => {
      // console.log(file);
      // console.log(insertFn)
    };
    // 编辑器实例，必须用 shallowRef
    const editorRef = shallowRef();
    // 内容 HTML
    const valueHtml = ref("");
    const toolbarConfig = {};
    const editorConfig = {
      placeholder: "请输入内容...",
      MENU_CONF: {
        uploadImage: {
          customUpload: update,
        },
      },
    };
    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
      const editor = editorRef.value;
      if (editor == null) return;
      editor.destroy();
    });

    const handleCreated = (editor) => {
      editorRef.value = editor; // 记录 editor 实例，重要！
    };
    return {
      editorRef,
      valueHtml,
      mode: "simple",
      toolbarConfig,
      editorConfig,
      handleCreated,
      update,
    };
  },
  // 数据源
  data() {
    return {
      courseId: "",
      annoList: [],
      // 是否可新增
      isMore: true,
      size: 3,
      page: 1,
      dialogVisible: false,
      changeDialogVisible: false,
      tempAnno: {},
      total: 0, //数据库总数
      currentTotal: 0, //当前显示总数
    };
  },
  created() {
    //将捕获到的参数进行首次保存（课程ID）
    this.courseId = this.getParams();
    this.getCount();
    this.getAnno();
    
  },
  //生命周期函数---
  //基本方法
  methods: {
    //获取当前时间
    getCurrentTime(stamp) {
      let time;
      if (stamp !== undefined) {
        time = new Date(stamp);
      } else {
        time = new Date();
      }
      let d = time.toLocaleDateString();
      let h = time.toLocaleTimeString();
      return `${d} ${h}`;
    },
    getParams() {
      const route = useRoute();
      let courseId = route.query.courseId;
      return courseId;
    },
    //获取公告
    getAnno() {
      let that = this;
      //发送请求 携带参数为课程ID 返回的数量固定 每次都push进annoList，返回值为空是isMore为false
      queryByPage(that.courseId, that.page, that.size).then((res) => {
        if (res.code == "200") {
        
          that.currentTotal += res.data.length;
          if (that.currentTotal >= that.total) that.isMore = false;
          res.data.forEach((item) => {
            item.createTime = that.getCurrentTime(item.createTime);
            this.annoList.push(item);
          });
        } else {
          ElMessage({
            type: "warning",
            message: "获取更多失败",
          });
        }
      });
    },
    // 总数
    getCount() {
      countAnno(this.courseId).then((res) => {
        if (res.code == 200) {
          this.total = res.data;
        } else {
          ElMessage({
            type: "error",
            message: "获取列表数失败",
          });
        }
      });
    },
    //打开创建公告
    creatAnnounce() {
      this.dialogVisible = true;
    },
    //发送公告 创建新公告
    deliverAnno() {
      let newAnno = {};
      newAnno.courseId = this.courseId;
      newAnno.context = this.editorRef.getHtml();
      addAnno(newAnno).then((res) => {
        if (res.code == 200) {
         newAnno.createTime= this.getCurrentTime( res.data.createTime);
         newAnno.noticeId=res.data.noticeId
          ElMessage({
            type: "success",
            message: "发布成功",
          });
          this.dialogVisible = false;
          this.editorRef.clear();
          this.annoList.unshift(JSON.parse(JSON.stringify(newAnno)))
        } else {
          ElMessage({
            type: "error",
            message: "新建失败",
          });
        }
      });
    },
    //修改公告 对应内容传入富文本
    editAnnounce(item) {
      this.tempAnno = item;
      this.valueHtml = item.context;
      //this.editorRef.setHtml("<p>hello <strong>world</strong></p>")
      this.changeDialogVisible = true;
    },
    deliverChangedAnno() {
      let that=this;
      //针对的是临时保存的tempAnno,直接将其
      that.tempAnno.context = that.editorRef.getHtml();
      that.tempAnno.createTime = "";
      //还需要发送请求把tempAnno传到后端修改处理 返回成功消息  清空 temAnno值
      console.log(that.tempAnno);
      editAnno(that.tempAnno).then((res) => {
        console.log(res);
        if (res.code == 200) {
          that.tempAnno.createTime= that.getCurrentTime( res.data.createTime)
          that.changeDialogVisible = false;
          that.editorRef.clear();
          ElMessage({
            type: "success",
            message: "修改成功",
          });
        } else {
          ElMessage({
            type: "error",
            message: "操作失败！",
          });
        }
      });
    },
    //删除公告
    deleteAnnounce(item) {
      let that = this;
      deleteAnnoByID(item.noticeId).then((res) => {
        if (res.code == 200) {
          let a = that.annoList.indexOf(item);
          that.annoList.splice(a, 1);
          //需要补充 从数据库中删除它
          //根据返回值进行输出对应提示
          ElMessage({
            showClose: true,
            message: "删除成功",
            type: "success",
          });
        } else {
          ElMessage({
            showClose: true,
            message: "删除失败",
            type: "error",
          });
        }
      });
    },
    //获取更多条记录
    getMore() {
      this.page++;
      this.getAnno();
    },
    // 取消
    cancelEvent() {
      ElMessage({
        type: "success",
        message: "取消成功",
      });
    },
  },
  //计算类型方法和其他方法的区别：有缓存。以内存换时间，适用于频繁使用的计算
    computed: {
    ...mapGetters({
       role: "getRole",
    })
  },
};
</script>

<style   scoped>
.qwe {
  display: flex;
}
.container {
  width: 80%;
  min-height: 500px;
  background: rgb(255, 255, 255);
}
.right-box {
  width: 20%;
}
.comment {
  margin-top: 10px;
}
.last-time {
  text-align: right;
}
.more {
  margin-top: 20px;
}
</style>